package org.jeecg.modules.iot.aio.thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 这里是一个注释
 *
 * @author scw
 * @version v1.0
 * @date
 */
public class Threads {

    public static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();
    public static final int CORE_POOL_SIZE = AVAILABLE_PROCESSORS * 1;
    public static final int MAX_POOL_SIZE_FOR_TIO = Integer.getInteger("TIO_MAX_POOL_SIZE_FOR_TIO", Math.max(CORE_POOL_SIZE * 3, 64));
    public static final int MAX_POOL_SIZE_FOR_GROUP	= Integer.getInteger("TIO_MAX_POOL_SIZE_FOR_GROUP", Math.max(CORE_POOL_SIZE * 16, 256));
    public static final long KEEP_ALIVE_TIME = 0L;																					//360000L;
    @SuppressWarnings("unused")
    private static final int QUEUE_CAPACITY = 1000000;
    private static ThreadPoolExecutor aioExecutor = null;

    /**
     * 初始化一个线程池
     * @return
     */
    public static ThreadPoolExecutor getGroupExecutor() {
        if(aioExecutor != null)return aioExecutor;
        synchronized (Threads.class) {
            if(aioExecutor != null)return aioExecutor;
            LinkedBlockingQueue<Runnable> runnableQueue = new LinkedBlockingQueue<>();
            String threadName = "aio-worker";
            DefaultThreadFactory threadFactory = DefaultThreadFactory.getInstance(threadName, Thread.MAX_PRIORITY);
            ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy();
            aioExecutor = new ThreadPoolExecutor(MAX_POOL_SIZE_FOR_GROUP, MAX_POOL_SIZE_FOR_GROUP, KEEP_ALIVE_TIME, TimeUnit.SECONDS, runnableQueue, threadFactory,
                    callerRunsPolicy);
            aioExecutor.prestartCoreThread();
            return aioExecutor;
        }
    }


}
